import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

const CATCH_URLS = ['m.ctrip.com/', 'm.ctrip.com/html5', 'm.ctrip.com/html5'];

class MyWebView extends StatefulWidget {
  final String url;
  final String? statusBarColor;
  final String title;
  final bool? hideAppBar;
  final bool backForbid;

  const MyWebView({
    super.key,
    required this.url,
    this.statusBarColor,
    required this.title,
    this.hideAppBar,
    this.backForbid = false,
  });

  @override
  _WebViewState createState() => _WebViewState();
}

class _WebViewState extends State<MyWebView> {
  late WebViewController _controller;
  bool _isLoading = true;
  bool exiting = false;

  @override
  void initState() {
    super.initState();
    // 初始化 WebView 插件
    _controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageStarted: (String url) {
            setState(() {
              _isLoading = true;
            });
          },
          onPageFinished: (String url) {
            setState(() {
              _isLoading = false;
            });
          },
          onHttpError: (HttpResponseError error) {
            print("HTTP Error: ${error}");
          },
          onWebResourceError: (WebResourceError error) {
            print("Web Resource Error: ${error.description}");
          },
          onNavigationRequest: (NavigationRequest request) {
            // if (_isToMain(request.url) && !exiting) {
            //   _controller.loadRequest(Uri.parse(widget.url));
            // } else {
            //   Navigator.pop(context);
            //   exiting = true;
            // }
            return NavigationDecision.navigate;
          },
        ),
      )
      ..loadRequest(Uri.parse(widget.url));
  }

  bool _isToMain(String url) {
    for (final value in CATCH_URLS) {
      if (url.endsWith(value)) {
        return true;
      }
    }
    return false;
  }

  @override
  Widget build(BuildContext context) {
    String statusBarColorStr = widget.statusBarColor ?? "ffffff";
    Color backButtonColor =
        (statusBarColorStr == 'ffffff') ? Colors.black : Colors.white;

    return Scaffold(
      body: Column(
        children: [
          _appBar(
              Color(int.parse('0xff' + statusBarColorStr)), backButtonColor),
          Expanded(
            child: Stack(
              children: [
                WebViewWidget(controller: _controller),
                if (_isLoading)
                  Center(
                    child: CircularProgressIndicator(),
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _appBar(Color backgroundColor, Color backButtonColor) {
    if (widget?.hideAppBar ?? false) {
      return Container(
        color: backgroundColor,
        height: 30,
      );
    }
    return Container(
      color: backgroundColor,
      padding: EdgeInsets.fromLTRB(0, 40, 0, 10),
      child: FractionallySizedBox(
        widthFactor: 1,
        child: Stack(
          children: [
            GestureDetector(
              onTap: () {
                if (widget.backForbid) return;
                Navigator.of(context).pop();
              },
              child: Container(
                margin: EdgeInsets.only(left: 10),
                child: Icon(
                  Icons.close,
                  color: backButtonColor,
                  size: 26,
                ),
              ),
            ),
            Positioned(
                left: 0,
                right: 0,
                child: Center(
                  child: Text(
                    widget.title ?? "",
                    style: TextStyle(color: backButtonColor, fontSize: 20),
                  ),
                ))
          ],
        ),
      ),
    );
  }
}
